package com.jp.knowledge.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.JpMainActivity;
import com.jp.knowledge.activity.SearchActivity;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.db.DBHelper;
import com.jp.knowledge.dialog.ComPopuWindow;
import com.jp.knowledge.dialog.HeadlineDragDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.logic.PositionKnowlegeDataLogic;
import com.jp.knowledge.model.HeadLine;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.PositionKnowlegeMode;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.util.TimeUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author jiayen     2017-06-07 14:38:18
 * 岗位知识fragment
 */
public class PositionKnowleageFragment extends BaseTabFragment implements View.OnClickListener, ResultSubscriber.OnResultListener {

    private static final int GET_SKILL_CODE = 0x01;
    private List<Fragment> fragments;

    private FileCacheManager fileCacheManager;
//    protected SkillModel skillModel;

    protected List<PositionKnowlegeMode>  models;

    private HeadlineDragDialog   dragDialog;

    private List<HeadLine>  headLines;
    private LocalBroadcastManager  localBroadcastManager;
    private LocalBroadCast localBroadCast;

    private PositionKnowlegeDataLogic  logic;

    private int lastPostion;

    @Override
    public void initView() {

        logic = PositionKnowlegeDataLogic.getInstance(mContext);
        logic.setCallkBack(new PositionKnowlegeDataLogic.SucdessCallkBack() {
            @Override
            public void done(List<PositionKnowlegeMode> mls) {
                models = mls;
                setView();
//                saveCache(models, getCachePath());
            }
        });


        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                logic.getKnowlegeData();
            }
        });
        IntentFilter intent = new IntentFilter();
        intent.addAction(LocalBroadCast.GET_LOGIN_INFO);
        intent.addAction(LocalBroadCast.USER_DATA_CHANGE);
        intent.addAction(LocalBroadCast.LOGOUT_SUCCESS_BROD);
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadcastManager.registerReceiver(localBroadCast,intent);

        dragDialog = new HeadlineDragDialog(mContext);
        dragDialog.setApplication(application);
        dragDialog.setDragItemHelper(new ComPopuWindow.DragItemHelper() {
            @Override
            public void drag(int fromPositon, int toPosition) {
                models.add(toPosition, models.remove(fromPositon));
//                fragments.add(toPosition, fragments.remove(fromPositon));
                lastPostion = toPosition;
            }

            @Override
            public void dragFinish() {
                setTabNames();
                viewPager.setCurrentItem(lastPostion);
                for(int i = 0; i < models.size(); i++){
                    ((PositionKnowleageItemFragment)fragments.get(i)).updateData(models.get(i));
                }
                //更新服务端的顺序
                JsonObject param = new JsonObject();
                param.add("data", new Gson().toJsonTree(headLines, new TypeToken<List<HeadLine>>() {}.getType()).getAsJsonArray());
                HttpHelper.getInstance(mContext).headLineUpdate(param, 0x00000016, PositionKnowleageFragment.this);
//                adapter.notifyDataSetChanged();
//                viewPager.setCurrentItem(lastPostion, false);
            }
        });

        dragDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {//保存排序后的缓存
//                setView();
//                viewPager.setCurrentItem(lastPostion, false);

                saveCache(models,getCachePath());
                DBHelper.getInstance().delete(HeadLine.class);
                DBHelper.getInstance().save(headLines);
                JsonObject param = new JsonObject();
                param.add("data", new Gson().toJsonTree(headLines, new TypeToken<List<HeadLine>>() {}.getType()).getAsJsonArray());
                //更新服务端的顺序
//                HttpHelper.getInstance(mContext).headLineUpdate(param, 0x00000016, PositionKnowleageFragment.this);
                tabView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent();
                        intent.setAction(LocalBroadCast.HEAD_LINE_SORT);
                        localBroadcastManager.sendBroadcast(intent);
                    }
                },1000);

            }
        });
        sortBtn.setOnClickListener(this);
        fileCacheManager = new FileCacheManager();
        readCache(null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localBroadCast);
    }

    private boolean showDragDialog = false;
    public void setShowDragDialog(boolean showDragDialog){
        this.showDragDialog = showDragDialog;
    }
    @Override
    public void onResume() {
        super.onResume();
        if(showDragDialog){
            showDragDialog = false;
            dragDialog.show();
        }
    }

    public int getCurPostion(){
        return  viewPager.getCurrentItem();
    }

    public PositionKnowlegeMode getSkillModel() {
        return models.get(viewPager.getCurrentItem());
    }


    /***
     * 对位提供
     * @return
     */
    public List<PositionKnowlegeMode> getModels() {
        return models;
    }

    @Override
    protected void initHead(View mView) {
        super.initHead(mView);
        topName.setText("岗位知识");
        rightIcon.setVisibility(View.VISIBLE);
        rightIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent(mContext, SearchActivity.class);
                intent.putExtra("id",models.get(viewPager.getCurrentItem()).getId());
                intent.putExtra("action",2);
                intent.putExtra("level",1);
                mContext.startActivity(intent);
            }
        });
    }
    /**
     * 获取fragment
     * @return
     */
    @Override
    protected List<Fragment> getFragments() {
        fragments = new ArrayList<>();
        if(models!=null) {

            int size = models.size();
            for (int i = 0; i < size; i++) {
                fragments.add(new PositionKnowleageItemFragment().newInstance(models.get(i)));
            }
        }
        return fragments;
    }

    @Override
    public void setTabNames() {
        if(models == null)
            return;
        List<String> tabTitles = new ArrayList<>();
        for(PositionKnowlegeMode positionKnowlegeMode : models)
            tabTitles.add(positionKnowlegeMode.getName());
        tabView.setTabItems(tabTitles);
    }

    private String getCachePath(){
        return mContext.getCacheDir() + "/skillCache_position_knowlege_all_"  + ".dat";
    }
    private void readCache(final String id){
        Observable.create(new Observable.OnSubscribe<List<PositionKnowlegeMode>>() {
            @Override
            public void call(Subscriber<? super List<PositionKnowlegeMode>> subscriber) {
                try {
                    List<PositionKnowlegeMode> data = (List<PositionKnowlegeMode>) fileCacheManager.readObject(logic.getCachePath());
                    subscriber.onNext(data);
                }catch (Exception e){

                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<PositionKnowlegeMode>>() {
                    @Override
                    public void onCompleted() {
//                        // 缓存超过10分钟则重新获取数据
//                        if(models == null )//|| System.currentTimeMillis()-skillModel.getCacheTime() > 1000*60*10
//                            getData(id);
                        File file = new File(logic.getCachePath());
                        if(file!=null) {
                            long lastTime = file.lastModified();//缓存最后修改时间
                            String time = TimeUtil.formatData(lastTime);
                            if (models == null || (System.currentTimeMillis() - lastTime) > 1000 * 60 * 5) {
                                logic.getKnowlegeData();
                            }
                        }
                    }
                    @Override
                    public void onError(Throwable e) {
                        onCompleted();
                    }
                    @Override
                    public void onNext(List<PositionKnowlegeMode> data) {
                        try {


                            models = data;
                            if (models == null) {//
                                models = PositionKnowlegeDataLogic.getModels();
                                if (models == null || models.size() == 0) {
                                    logic.getKnowlegeData();
                                } else {

                                    setView();
                                }
                            } else {
                                PositionKnowlegeDataLogic.setModels(models);
                                setView();
                            }
                        }catch (Exception e) {

                        }
                        onCompleted();
                    }
                });
    }


    private void getData(final String id){
        JsonObject param = new JsonObject();
        if(id != null)
            param.addProperty("id", id);
        HttpHelper.getInstance(mContext).getSkill(param, GET_SKILL_CODE, new ResultSubscriber.OnResultListener() {
            @Override
            public void onStart(int requestType) {}
            @Override
            public void onCompleted(int requestType) {}
            @Override
            public void onError(int requestType) {
                onCompleted(requestType);
            }
            @Override
            public void onNext(IModel data, int requestType) {
                if(data.getErrcode() != 0){
                    ToasUtil.toast(mContext, data.getMessage());
                    onError(requestType);
                } else if(requestType == GET_SKILL_CODE){
                    models = data.getList(PositionKnowlegeMode.class);
                    setView();
                    saveCache(models, getCachePath());
                }
            }
        });
    }

    private void saveCache(final Object data, final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                fileCacheManager.wirteObject(data, path);
            }
        }).start();
    }
    private void setView() {
        initTabLayout();

        initHeadLines();
        dragDialog.updateData(headLines);
    }

    private void initHeadLines(){
        if(models!=null){
            headLines = new ArrayList<>();
            for (PositionKnowlegeMode model: models) {
                HeadLine hedLine = new HeadLine();
                hedLine.setTypeName(model.getName());
//                hedLine.setId(model.getId());
                hedLine.setTypeId(model.getNavType());
                headLines.add(hedLine);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.sort_btn:
                dragDialog.show();
                break;

            default:
                break;
        }
    }

    @Override
    public void onStart(int requestType) {

    }

    @Override
    public void onCompleted(int requestType) {

    }

    @Override
    public void onError(int requestType) {

    }

    @Override
    public void onNext(IModel data, int requestType) {

    }
}
